package com.naiterui.ehp.bs.cms.modules.user.controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.validation.constraints.NotNull;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.naiterui.ehp.bp.constants.SwaggerTag;
import com.naiterui.ehp.bp.security.annotation.AnonymousPostMapping;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.utils.date.DateUtil;
import com.naiterui.ehp.bs.cms.common.controller.AbstractController;
import com.naiterui.ehp.bs.cms.common.utils.ConfigUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(tags = {SwaggerTag.CMS + SwaggerTag.USER})
@RestController
@RequestMapping("/storage")
@Slf4j
public class StorageController extends AbstractController {

    @Value("${file.base.prefix}")
    private String fileBasePrefix;

    /**
     * 病历详情信息
     *
     * @return
     * @throws BusinessException
     */
    @ResponseBody
    @PostMapping
    @ApiOperation("文件上传")
    @AnonymousPostMapping
    @ApiImplicitParams({
        @ApiImplicitParam(name = "file", value = "文件", dataType = "__file", paramType = "form", required = true)
    })
    public String upload(@NotNull(message = "上传文件不能为null") MultipartFile file) {
        String extName = FilenameUtils.getExtension(file.getOriginalFilename());
        String fileName = UUID.randomUUID() + "." + extName;
        String filepath = "/cms/storage/" + DateUtil.getCurrentCustomizeFormatDate(DateUtil.DATE_FORMAT_BY_DIAGONAL) + "/" + fileName;
        File storageFile = new File(fileBasePrefix + filepath);
        try {
            FileUtils.forceMkdirParent(storageFile);
            FileUtils.copyInputStreamToFile(file.getInputStream(), storageFile);
        } catch (IOException e) {
            log.error("文件上传失败：", e);
        }

        String imgHost = ConfigUtil.getString("ehp.domain.img");
        return imgHost + filepath;
    }
}
